package 蓝桥杯算法;

import java.util.LinkedList;
import java.util.Queue;

public class day31 {
    public static void main(String[] args) {
        //古岛的总面积
        int m=4;
        int n=5;
        int[][]graph={{1,1,0,0,0},{1,1,0,0,0},{0,0,1,0,0},{0,0,0,1,1}};
        int result=0;
        int count=0;
        for(int i=0;i<m;i++){//遍历第一行
            if(graph[i][0]==1){
                bfs(graph,i,0,count);
            }
            if(graph[i][m-1]==1){
                bfs(graph,i,m-1,count);
            }
        }
        for(int j=0;j<m;j++){
            if(graph[0][j]==1){
                bfs(graph,0,j,count);
            }
           else if(graph[n-1][j]==1){
                bfs(graph,n-1,j,count);
            }
        }
        count=0;//在此刻置为零
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(graph[i][j]==1){
                    bfs(graph,i,j,count);
                    //会把剩下的所有孤岛的值全部加起来
                }
            }
        }

    }
    //把不是孤岛屿全部置零
    public static void bfs(int[][] grid, int x, int y,int count){
        int[][] dir = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
        Queue<int[]>queue=new LinkedList<>();
        queue.add(new int[]{x,y});
        grid[x][y]=0;
        while (!queue.isEmpty()){
            int[] temp=queue.poll();
            int curx=temp[0];
            int cury=temp[1];
            for(int i=0;i<4;i++){
                int nextx = curx + dir[i][0];
                int nexty = cury + dir[i][1];
                if (nextx < 0 || nextx >= grid.length || nexty < 0 || nexty >= grid[0].length) continue; // 越界了，直接跳过
                if (grid[nextx][nexty] == 1) {
                    //符合条件的加加
                    count++;
                    queue.add(new int[]{nextx, nexty});
                    grid[nextx][nexty] = 0;
                }
            }
        }
    }

}
